package com.zjw.zy.base.special;

import android.content.Intent;

import androidx.annotation.NonNull;

import com.zjw.zy.CrashActivity;
import com.zjw.zy.utils.AppUtils;

import java.util.Arrays;

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/9/29 13:13
 * <p>
 * 异常未捕获的处理
 */
public final class UnCatcherHandler implements Thread.UncaughtExceptionHandler {

    private static final UnCatcherHandler INSTANCE = new UnCatcherHandler();

    public static UnCatcherHandler getInstance() {
        return INSTANCE;
    }

    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        Intent intent = new Intent(AppUtils.getApp(), CrashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(CrashActivity.CRASH_MESSAGE_KEY, e.getMessage() + Arrays.toString(e.getStackTrace()));
        AppUtils.getApp().startActivity(intent);
        System.exit(0);
    }


    /**
     * 测试用
     */
    public void throwTestException() {
        throw new RuntimeException("test exception!");
    }


    public void init() {
        Thread.setDefaultUncaughtExceptionHandler(this);
    }
}
